package com.ruoyi.web.controller.comment;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.client.domain.SysBuy;
import com.ruoyi.client.domain.SysSell;
import com.ruoyi.client.service.ISysBuyService;
import com.ruoyi.client.service.ISysSellService;
import com.ruoyi.common.annotation.Anonymous;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.text.DecimalFormat;
import java.time.LocalTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 前后端交互的类实现消息的接收推送(自己发送给另一个人)
 *
 * @ServerEndpoint(value = "/test/oneToOne") 前端通过此URI 和后端交互，建立连接
 */
@Slf4j
@Anonymous
@ServerEndpoint(value = "/test/oneToOne")
@Component
public class OneToOneWebSocket {

    private static ISysBuyService iSysBuyService;
    @Autowired
    public void setiSysBuyService(ISysBuyService iSysBuyService) {
        OneToOneWebSocket.iSysBuyService = iSysBuyService;
    }

    /** 记录当前在线连接数 */
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    /** 存放所有在线的客户端 */
    private static Map<String, Session> clients = new ConcurrentHashMap<>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        onlineCount.incrementAndGet(); // 在线数加1
        clients.put(session.getId(), session);
        log.info("有新连接加入：{}，当前在线人数为：{}", session.getId(), onlineCount.get());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        onlineCount.decrementAndGet(); // 在线数减1
        clients.remove(session.getId());
        log.info("有一连接关闭：{}，当前在线人数为：{}", session.getId(), onlineCount.get());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     *            客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) throws JsonProcessingException, InterruptedException {
        // 处理收到的消息
        log.info("Received message from client: {}", message);

        // 解析消息内容，获取前端传过来的参数
        ObjectMapper objectMapper = new ObjectMapper();

        JsonNode jsonNode = objectMapper.readTree(message);
        String symbol = jsonNode.get("symbol").asText();
        //String trade = jsonNode.get("trade").asText();
        //boolean b = isWithinTimeRange();
        while (true){
            Thread.sleep(6000);
            String s = HttpUtil.get("https://api.mairui.club/hsrl/ssjy/" + symbol + "/b887d4403688d5e65a");
            JSONObject jsonObject = JSONUtil.parseObj(s);
            HashMap<String, Object> map = new HashMap<>();
            // 获取特定时间段（9:30-11:30和13:00-15:00）的股票分时图数据并存放到Map中
            ArrayList<Map> maps = processTimeRangeData(jsonObject, map);
            this.sendMessage(new ObjectMapper().writeValueAsString(maps), session);
        }
    }

    private boolean isWithinTimeRange() {
        // 在这里编写判断逻辑，判断当前时间是否在指定时间范围内
        // 可以使用Java的日期时间类库来比较时间
        LocalTime currentTime = LocalTime.now();
        LocalTime morningStartTime = LocalTime.parse("09:30");
        LocalTime morningEndTime = LocalTime.parse("11:30");
        LocalTime afternoonStartTime = LocalTime.parse("13:00");
        LocalTime afternoonEndTime = LocalTime.parse("15:30");

        boolean isMorningTime = !currentTime.isBefore(morningStartTime) && !currentTime.isAfter(morningEndTime);
        boolean isAfternoonTime = !currentTime.isBefore(afternoonStartTime) && !currentTime.isAfter(afternoonEndTime);

        return isMorningTime || isAfternoonTime;
    }



    public ArrayList<Map> processTimeRangeData(JSONObject jsonObject, HashMap<String, Object> map){
        ArrayList<Map> maps = new ArrayList<>();
        final Object fm = jsonObject.get("fm");
        final Object h = jsonObject.get("h");
        final Object js = jsonObject.get("js");
        final Object lb = jsonObject.get("lb");
        final Object l = jsonObject.get("l");
        final Object lt = jsonObject.get("lt");
        final Object o = jsonObject.get("o");
        final Object pe = jsonObject.get("pe");
        final Object pc = jsonObject.get("pc");
        final Object p = jsonObject.get("p");
        final Object sz = jsonObject.get("sz");
        final Object cje = jsonObject.get("cje");
        final Object ud = jsonObject.get("ud");
        final Object v = jsonObject.get("v");
        final Object yc = jsonObject.get("yc");
        final Object zf = jsonObject.get("zf");
        final Object zs = jsonObject.get("zs");
        final Object sjl = jsonObject.get("sjl");
        final Object zdf60 = jsonObject.get("zdf60");
        final Object zdfnc = jsonObject.get("zdfnc");
        final Object t = jsonObject.get("t");
        map.put("fm",fm);
        map.put("h",h);
        map.put("js",js);
        map.put("lb",lb);
        map.put("l",l);
        map.put("lt",lt);
        map.put("o",o);
        map.put("pe",pe);
        map.put("pc",pc);
        map.put("p",p);
        map.put("sz",sz);
        map.put("cje",cje);
        map.put("ud",ud);
        map.put("v",v);
        map.put("yc",yc);
        map.put("zf",zf);
        map.put("zs",zs);
        map.put("sjl",sjl);
        map.put("zdf60",zdf60);
        map.put("zdfnc",zdfnc);
        map.put("t",t);
        maps.add(map);
        System.err.println(map);
        return maps;
    }





    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 服务端发送消息给客户端
     */
    private void sendMessage(String message, Session toSession) {
        try {
            log.info("服务端给客户端[{}]发送消息[{}]", toSession.getId(), message);
            toSession.getBasicRemote().sendText(message);
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败：{}", e);
        }
    }

}
